<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= productName %></title>
    <style>
      /* 重置样式 */
      body, html {
        margin: 0;
        padding: 0;
        height: 100%;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", "Arial", "Noto Sans", "sans-serif";
      }
      
      #app {
        height: 100%;
        position: relative;
        overflow: hidden;
      }
      
      /* Error 和 Loading 样式 */
      .miniblink-error, .miniblink-loading {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: rgba(255, 255, 255, 0.9);
        z-index: 9999;
      }
      
      .miniblink-error-title, .miniblink-loading-title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 16px;
        color: #333;
      }
      
      .miniblink-error-message {
        font-size: 14px;
        color: #f56c6c;
        margin-bottom: 16px;
        text-align: center;
        max-width: 80%;
      }
      
      .miniblink-loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #409eff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 16px;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    </style>
    
    <!-- 自定义组件样式 -->
    <style>
    /* Easy Window StyleSheet v1.0.1 */
    <% if (typeof componentStyles === 'string') { %><%= componentStyles %><% } %>
    </style>
    
    <style>
      /* 确保App组件填满整个容器 */
      .main-container {
        width: 100%;
        height: 100%;
        position: relative;
        overflow: hidden;
      }
      
      /* 预览渲染区域与导出一致 */
      .preview-render-area {
        position: relative;
        width: 100%;
        height: 100%;
      }
    </style>
    
    <!-- Vue 3 CDN 引入 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    
    <!-- Element Plus 引入 -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <script src="https://unpkg.com/element-plus"></script>
  </head>
  <body>
    <div id="app">
      <!-- Vue3 模板将在这里渲染 -->
      <div v-if="isLoading" class="miniblink-loading">
        <div class="miniblink-loading-spinner"></div>
        <div class="miniblink-loading-title">加载中...</div>
      </div>
      
      <div v-if="errorMessage" class="miniblink-error">
        <div class="miniblink-error-title">错误</div>
        <div class="miniblink-error-message">{{ errorMessage }}</div>
      </div>
      
      <div v-if="!isLoading && !errorMessage" class="main-container">
        <div class="preview-render-area">
          <!-- 动态渲染组件 -->
          <template v-for="component in components" :key="component.id">
            <component
              :is="componentMap[component.type]"
              v-bind="component.props"
              :data-component-id="component.id"
              :style="component.style"
              @click="handleComponentClick(component)"
              v-model="componentStates[component.id]"
            />
          </template>
        </div>
      </div>
    </div>

    <script>
      // 创建miniBridge - 通信桥接器
      window.miniBridge = {
        _eventHandlers: {},
        
        // 注册事件处理器
        on: function(eventName, handler) {
          if (!this._eventHandlers[eventName]) {
            this._eventHandlers[eventName] = [];
          }
          this._eventHandlers[eventName].push(handler);
          
          console.log(`Registered handler for event: ${eventName}`);
          return this;
        },
        
        // 移除事件处理器
        off: function(eventName, handler) {
          if (!this._eventHandlers[eventName]) return this;
          
          if (handler) {
            const index = this._eventHandlers[eventName].indexOf(handler);
            if (index !== -1) {
              this._eventHandlers[eventName].splice(index, 1);
            }
          } else {
            // 移除所有该事件的处理器
            delete this._eventHandlers[eventName];
          }
          
          return this;
        },
        
        // 向宿主应用发送事件
        emit: function(eventName, data) {
          console.log(`Emitting event: ${eventName}`, data);
          
          try {
            // 针对Miniblink/CEF集成
            if (window.external && typeof window.external.CallCSharpOrOther === 'function') {
              const message = JSON.stringify({
                event: eventName,
                data: data || {}
              });
              window.external.CallCSharpOrOther(message);
            } 
            // 针对易语言Miniblink库
            else if (window.external && typeof window.external.notify === 'function') {
              const message = JSON.stringify({
                event: eventName,
                data: data || {}
              });
              window.external.notify(message);
            }
            // 浏览器调试用
            else {
              console.warn(`No host bridge available for event: ${eventName}`);
              
              // 在浏览器环境中特殊处理ready事件
              if (eventName === 'ready') {
                // 在浏览器中，模拟一个测试数据响应
                setTimeout(() => {
                  this._handleHostMessage({
                    event: 'updateRootComponent',
                    data: {
                      id: 'root',
                      type: 'div',
                      style: 'padding: 20px',
                      children: [
                        {
                          id: 'test-button',
                          type: 'el-button',
                          props: {
                            type: 'primary',
                            text: 'Test Button'
                          },
                          style: ''
                        }
                      ]
                    }
                  });
                }, 500);
              }
            }
          } catch (error) {
            console.error(`Error emitting event ${eventName}:`, error);
          }
          
          return this;
        },
        
        // 处理来自宿主的消息
        _handleHostMessage: function(message) {
          try {
            const { event, data } = typeof message === 'string' ? JSON.parse(message) : message;
            
            console.log(`Received host event: ${event}`, data);
            
            if (this._eventHandlers[event]) {
              this._eventHandlers[event].forEach(handler => {
                try {
                  handler(data);
                } catch (handlerError) {
                  console.error(`Error in handler for ${event}:`, handlerError);
                }
              });
            }
          } catch (error) {
            console.error('Error processing host message:', error);
          }
        }
      };
      
      // 处理来自C#/易语言等的消息
      window.MiniblinkCallback = function(messageStr) {
        try {
          window.miniBridge._handleHostMessage(messageStr);
        } catch (error) {
          console.error('Error in MiniblinkCallback:', error);
        }
      };
      
      // 创建Vue应用
      const appData = {
        components: <% if (typeof components === 'object' && Array.isArray(components)) { %><%= JSON.stringify(components) %><% } else { %>[]<% } %>,
        componentStates: {}, // 存储组件状态
        componentMap: {
          'el-button': ElementPlus.ElButton,
          'el-input': ElementPlus.ElInput,
          'el-select': ElementPlus.ElSelect,
          'el-option': ElementPlus.ElOption,
          'el-radio': ElementPlus.ElRadio,
          'el-radio-group': ElementPlus.ElRadioGroup,
          'el-checkbox': ElementPlus.ElCheckbox,
          'el-checkbox-group': ElementPlus.ElCheckboxGroup,
          'el-switch': ElementPlus.ElSwitch,
          'el-slider': ElementPlus.ElSlider,
          'el-date-picker': ElementPlus.ElDatePicker,
          'el-time-picker': ElementPlus.ElTimePicker,
          'el-form': ElementPlus.ElForm,
          'el-form-item': ElementPlus.ElFormItem,
          'el-table': ElementPlus.ElTable,
          'el-table-column': ElementPlus.ElTableColumn,
          'el-pagination': ElementPlus.ElPagination,
          'el-tabs': ElementPlus.ElTabs,
          'el-tab-pane': ElementPlus.ElTabPane,
          'el-dialog': ElementPlus.ElDialog,
          'el-card': ElementPlus.ElCard,
          'el-carousel': ElementPlus.ElCarousel,
          'el-carousel-item': ElementPlus.ElCarouselItem,
          'el-collapse': ElementPlus.ElCollapse,
          'el-collapse-item': ElementPlus.ElCollapseItem,
          'div': 'div',
          'span': 'span',
          'p': 'p',
          'h1': 'h1',
          'h2': 'h2',
          'h3': 'h3',
          'h4': 'h4',
          'h5': 'h5',
          'h6': 'h6',
          'img': 'img'
        },
        isLoading: true,
        errorMessage: null
      };
      
      // 创建Vue应用
      const app = Vue.createApp({
        data() {
          return appData;
        },
        created() {
          // 为每个组件初始化状态，如switch默认值等
          this.components.forEach(comp => {
            if (['el-switch', 'el-checkbox', 'el-radio'].includes(comp.type)) {
              this.componentStates[comp.id] = comp.props.modelValue || comp.props.value || false;
            } else if (['el-input', 'el-select'].includes(comp.type)) {
              this.componentStates[comp.id] = comp.props.modelValue || comp.props.value || '';
            } else if (['el-slider'].includes(comp.type)) {
              this.componentStates[comp.id] = comp.props.modelValue || comp.props.value || 0;
            }
          });
        },
        mounted() {
          // 应用加载完成
          this.isLoading = false;
          
          // 通知宿主应用就绪
          window.miniBridge.emit('app:ready', { count: this.components.length });
          
          // 注册miniBridge事件处理器
          window.miniBridge.on('updateComponent', this.handleUpdateComponent);
        },
        methods: {
          // 组件点击处理
          handleComponentClick(component) {
            console.log('Component clicked:', component);
            window.miniBridge.emit('component:click', {
              id: component.id,
              type: component.type
            });
          },
          
          // 处理组件更新
          handleUpdateComponent(data) {
            try {
              const componentIndex = this.components.findIndex(c => c.id === data.id);
              if (componentIndex !== -1) {
                // 更新组件属性
                Object.assign(this.components[componentIndex], data);
                console.log('Updated component:', this.components[componentIndex]);
              } else {
                console.warn('Component not found for update:', data.id);
              }
            } catch (error) {
              console.error('Error updating component:', error);
            }
          }
        },
        watch: {
          // 监听组件状态变化
          componentStates: {
            deep: true,
            handler(newStates, oldStates) {
              for (const [id, value] of Object.entries(newStates)) {
                if (oldStates[id] !== value) {
                  // 找到变化的组件
                  const component = this.components.find(c => c.id === id);
                  if (component) {
                    // 发送状态变化事件
                    window.miniBridge.emit('component:change', {
                      id: component.id,
                      type: component.type,
                      value: value
                    });
                  }
                }
              }
            }
          }
        }
      });
      
      // 使用Element Plus插件
      app.use(ElementPlus);
      
      // 挂载应用
      app.mount('#app');
    </script>
  </body>
</html> 